package cn.com.bsfit.netty.req;

import cn.com.bsfit.netty.exception.DefaultException;
import cn.com.bsfit.netty.utils.StringHelper;
import cn.com.bsfit.netty.utils.XmlToMapUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 类名 XmlReqData2Map
 * 描述 将XML格式的流数据转化为Map
 *
 * @author hedonglin
 * @version 1.0
 * @date 2019/9/27 10:27
 */
@SuppressWarnings("all")
@Component(value = "xmlReqData2Map")
@Slf4j
public class XmlReqData2Map implements ReqData2MapStrategy{
    /**
     * 首部字段
     */
    private ThreadLocal<String> currTopField = new ThreadLocal<>();

    @Override
    public Map<String, Object> reqData2Map(String msg) throws DefaultException {
        try {
            //解析为XML
            Map<String, Object> map = XmlToMapUtil.xml2map(msg.trim(), false);
            log.info("将消息转换为XML数据成功");
            // 获取顶层字段(XML一定具有顶层字段)
            String rootKey = XmlToMapUtil.getRootKey(msg);
            if (StringHelper.isNotBlank(rootKey)){
                // 当前消息的顶层标签
                currTopField.set(rootKey);
            }else {
                currTopField.set("");
            }
            return map;
        }catch (Exception e){
            throw new DefaultException("将消息转换为XML数据失败");
        }
    }

    @Override
    public String getCurrTopField() {
        return currTopField.get();
    }
}
